/**
 * 
 */
package com.theydream.qeechain.battle;

import java.util.Map;
import java.util.PriorityQueue;

import com.theydream.qeechain.globaldata.GlobalData;
import com.theydream.qeechain.globaldata.definition.BattleQee;
import com.theydream.qeechain.globaldata.definition.Effect;

/**
 * @author Rocky
 *
 */
public class SequenceLogic {
	
	private PriorityQueue<Move> sequence;
//	private List<Move> controlRef;

	/**
	 * Initialize the sequence with pets' agility
	 */
	public SequenceLogic() {
		sequence = new PriorityQueue<Move>();
//		controlRef = new ArrayList<Move>();
		
		Map<String, BattleQee> pets = GlobalData.getInstance().getPetListBattle();
		for (Map.Entry<String, BattleQee> entry : pets.entrySet())	{
			Move move = new Move(entry.getValue().getQee().getStat().get("SPEED"), entry.getKey(), "0", null);
			sequence.add(move);
//			controlRef.add(move);
		}
	}
	
	// Return Move of next pet
	public Move getNextMove()	{
		Move next = sequence.poll();
		
		for (Move move : sequence)	{
			move.decrement(next.getTime());
		}

		/* TODO: Do it somewhere else
		// If selecting skill/consumable, add the pet back to sequence
		if ("1".equals(next.getType()))	{
			next.reset();
			sequence.add(next);
		}
*/		
		return next;	
	}
	
	public Move peekNextMove()	{
		Move next = sequence.peek();
		
		return next;
	}
	
	// Add a new Effect release move
	public void addEffectReleaseMove(String _qid, Effect _effect){
		Move move = new Move(_effect.getDelay(), _qid, "1", _effect);
		
		// Cancel scheduled movement if necessary
		sequence.add(move);
	}
	
	// Add a new control move
	public void addControlMove(String _qid, int _t)	{
		Move move = new Move(_t, _qid, "0", null);
		
		sequence.add(move);
	}
	
	// Add move to sequence
	public void addMove(Move move)	{
		sequence.add(move);
	}

}

class Move implements Comparable<Move>	{
	private int baseTime;
	private int time;
	private String qid;			// 0 for player, 1 for computer
	private String type; 		// 0 for select skill/consumable, 1 for release skill/consumable
	private Effect effect;
	
	public Move(int _t, String _qid, String _type, Effect _effect)	{
		baseTime = time = _t;
		qid = _qid;
		type = _type;
		effect = _effect;
	}
	
	public void increment(int _t)	{
		time += _t;
	}
	
	public void decrement(int _t)	{
		time -= _t;
	}
	
	public int getTime()	{
		return time;
	}
	
	public void setBaseTime(int _t)	{
		baseTime = _t;
	}
	
	public void reset()	{
		time = baseTime;
	}
	
	public String getPetID()	{
		return qid;
	}
	
	public String getType()	{
		return type;
	}
	
	public Effect getEffect()	{
		return effect;
	}

	@Override
	public int compareTo(Move otherMove) {
		return time - otherMove.getTime();
	}
	
}